package c4.billing.cyclemanager;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class BillingUI {
	Statement stmtAccounts, stmtPhones, stmtCharges, stmtRates;
	ResultSet rsAccounts, rsPhones, rsCharges, rsRates;
	String query, accountNum, phone, type;
	double calls, voicemail, threeWay, callerId, taxes, duration;
	double lineCharges, lineTaxes, bill;
	String output = "";
	
	
    public BillingUI()
    {
    	try {
	    	/*
			 * Setup database objects
			 */
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			
		    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/corporate?" + 
		                                   "user=c4_user&password=p@ssw0rd");
		    /*
		     * Setup all the statement objects;
		     */
			stmtAccounts = conn.createStatement();
			stmtPhones = conn.createStatement();
			stmtCharges = conn.createStatement();
			stmtRates = conn.createStatement();
			
			System.out.println("--WELCOME TO THE BILLING SYSTEM--\n");
    	}
    	catch(Exception e) {
    		e.printStackTrace();
    		System.exit(1);
    	}
    	
        boolean keepLooping = true;
        int choice = -1;
       
       
        while(keepLooping)
        {
            displayMainMenu();
            choice = getChoice(1,3);
            if (choice == 3)
            {
                keepLooping = false;
            }
            else if (choice == 1)
            {
                System.out.println("\nOpen customers account");
                showCustomerAccount();
                
            }
            else if (choice == 2)
            {
                new CycleManager();
            	System.out.println("\n>>Cycle Manager Simulation Complete\n");
            }
        }
    }
       
    private void showCustomerAccount() {
    	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    	String accountNumber, pin, query;
    	boolean continueAsking = true;
    	boolean keepDisplaying = true;
    	int choice;
    	String newAmount = "";
    	
    	output = "";
    	
		while(continueAsking) {
			try {
				System.out.print("Enter Account #: ");
				accountNumber = br.readLine();
				System.out.print("Enter Pin #: ");
				pin = br.readLine();
				
				query = "SELECT * FROM account_information " +
						"WHERE account_number=" + accountNumber + " AND pin='" + pin + "';";
				
				rsAccounts = stmtAccounts.executeQuery(query);
				
				if(rsAccounts.next()) {
					displayBill();
					while(keepDisplaying) {
						displayCustomerMenu();
						choice = getChoice(1,2);
					
						if(choice == 1) {
							System.out.print("\nEnter new amount: ");
							newAmount = br.readLine();
							
							query = "DELETE FROM bills WHERE account_number=" + accountNumber + ";";
							
							stmtRates.execute(query);
							
							query = "INSERT INTO bills VALUES (" + accountNumber + "," + newAmount + ");";
							
							stmtRates.execute(query);
							
							displayBill();
							
							
						}
						else {
							continueAsking = false;
							keepDisplaying = false;
						}
					}
				}
				else {
					System.out.println("Customer not found in database. Please try again\n");
				}	
			
			}
			catch(Exception e) {
				System.out.println(e);
			}
		}
		
		
	}

	private void displayBill() {
		String output = "";
		output += "\n\n\t\t\tCUSTOMER INVOICE\n";
		output += "\t\t\t----------------\n\n";
		
		try {
		output += "Account Number:\t " + rsAccounts.getString("account_number") + "\n";
		output += "Name:\t\t " + rsAccounts.getString("name") + "\n";
		output += "Address:\t " + rsAccounts.getString("street") + "\n";
		output += "\t\t " + rsAccounts.getString("city") + ", " + rsAccounts.getString("state");
		output += " " + rsAccounts.getString("zip") + "\n\n";
		
		/*
		 * Determine what services they have
		 */
		output += "Monthly services on account\n";
		output += "Voicemail:\t";
		if(rsAccounts.getString(Constants.VOICEMAIL).equals("Y"))
			output += "Y\n";
		else
			output += "N\n";
		
		output += "Caller ID:\t";
		
		if(rsAccounts.getString(Constants.CALLER_ID).equals("Y"))
			output += "Y\n";
		else
			output += "N\n";
		
		output += "Three Way:\t";

		if(rsAccounts.getString(Constants.THREE_WAY).equals("Y"))
			output += "Y\n";
		else
			output += "N\n";
		
		output += "\n";
		
		/*
		 * Loop through the charges per phone
		 */
		accountNum = rsAccounts.getString(Constants.ACCOUNT_NUMBER);
		
		query = "SELECT * FROM charges " +
				"WHERE account_number=" + accountNum + ";";
		
		rsCharges = stmtCharges.executeQuery(query);
		
		output += "Overview of charges per line\n";
		
		while(rsCharges.next()) {
			output += "Line: " + rsCharges.getString("phone_number") + " - $";
			output += (rsCharges.getDouble("charges") + rsCharges.getDouble("taxes"));
			output += "\n";
		}
		
		/*
		 * Loop through the phone lines associated with this account number
		 */

		output += "\nDetailed line information\n";
		
		query = "SELECT phone_number FROM phone_number_listing " +
				"WHERE account_number=" + accountNum + ";";

		rsPhones = stmtPhones.executeQuery(query);
		
		while(rsPhones.next()) {
			phone = rsPhones.getString(Constants.PHONE_NUMBER);
			
			output += "Line: " + phone + "\n";
			
			/*
			 * Loop through the calls associated with this phone number
			 */
			query = "SELECT * " +
					"FROM call_log " +
					"WHERE phone_number=" + phone + ";";
			
			rsCharges = stmtCharges.executeQuery(query);
			
			/*
			 * Show the calls for this line
			 */
			while(rsCharges.next()) {
				output += "\t";
				output += rsCharges.getString("date_made") + " - ";
				output += rsCharges.getString("other_number") + " - ";
				output += rsCharges.getString("duration") + "\n";
			}
		}
		
		/*
		 * Display total due for this account
		 */
		query = "SELECT bill FROM bills WHERE account_number=" + accountNum + ";";
		
		rsCharges = stmtCharges.executeQuery(query);
		
		output += "\nTotal due: $";
		
		if(rsCharges.next())
			output += rsCharges.getString("bill");
		else
			output += "0.00";
		System.out.println(output);
		}
		catch(Exception e) {
			System.out.println("Customer bill couldn't be displayed...");
		}
		
	}

	private void displayMainMenu()
    {
        System.out.println();
        System.out.println("Main Menu");
        System.out.println("1. View Customer Account");
        System.out.println("2. Simulate CycleManager Run");
        System.out.println("3. Quit");
    }
	
	private void displayCustomerMenu()
    {
        System.out.println();
        System.out.println("Customer Account Menu");
        System.out.println("1. Update Total Due");
        System.out.println("2. Main Menu");
    }
   
    private int getChoice(int min, int max)
    {
       
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        boolean isValidChoice = false;
        int choice = -1;
        String userInput = "";
       
        do
        {
            try {
                System.out.print("Choose: ");
                userInput = br.readLine();
                choice = Integer.valueOf(userInput);
                if (choice <= max && choice >= min)
                    isValidChoice = true;
                else
                	System.out.println("Invalid Choice. Select again.");
            } catch (Exception e) {
                System.out.println("Invalid Choice. Select again.");
            }
        } while(!isValidChoice);
       
        return choice;
    }

    public static void main(String [] args)
    {
        new BillingUI();
    }

}